/******************* (C) COPYRIGHT 2022 CHU WEI TENG ***********************************************
**
**------------------ File Info ---------------------------------------------------------------------
** File name:      dwin_heap.c
** modified Date:  2022-05-10
** Last Version:   V1.0
** Descriptions: 
** 
**------------------ Modfication  log --------------------------------------------------------------
** Date       Who            Rev        Comments
----------------------------------------------------------------------------------------------------
   22/05/10  chuwt@qq.com    V1.00      created

****************************************************************************************************/
#include "dwin_heap.h"

static  volatile uint32_t   heap_start = 0;
static  volatile uint32_t   heap_end = 0;
static  volatile uint32_t   *heap_buff = NULL;

void dwin_heap_init(void* buffer, uint32_t length)
{
    heap_start = (uint32_t )buffer;
    heap_end =  heap_start + length;
    heap_buff = (uint32_t *)(heap_end & 0xFFFFFFFC);
}

void* dwin_heap_malloc(uint32_t size)
{
    uint32_t right = (uint32_t)heap_buff;
    uint32_t left  = 0;
    void*    ptr = NULL;
    
    if ((right > heap_start) && (size > 0))
    {
        left = right - heap_start;
        
        if (left >= size)
        {
            right     = (uint32_t)heap_buff;
            right    -= (((size - 1) & (0xFFFFFFFC)) + 4);
            heap_buff = (uint32_t *)right;
            ptr       = (void *)heap_buff;
        }
    }
    return ptr;
}
